<?php
/**
 # com_jvframework - JV Framework
 # @version		1.5.x
 # ------------------------------------------------------------------------
 # author    Open Source Code Solutions Co
 # copyright Copyright (C) 2011 joomlavi.com. All Rights Reserved.
 # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL or later.
 # Websites: http://www.joomlavi.com
 # Technical Support:  http://www.joomlavi.com/my-tickets.html
-------------------------------------------------------------------------*/

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.cache.cache');

class JVHooks extends JObject {
    protected $options;
    protected $layouts;
    
    /**
     * Array of Header <link> tags
     */
	protected $_links = array();
    
    /**
	 * Array of linked scripts
     */
    protected $_scripts = array();
    
    /**
	 * Array of scripts placed in the header	 
	 */
    protected $_script = array();
    
    /**
	 * Array of linked style sheets	
	 */
    protected $_styleSheets = array();
    
    /**
	 * Array of included style declarations
	 *	
	 */
    protected $_style = array();
    
    /**
	 * Array of included style declarations
	 *	
	 */
    protected $_custom = array();
    
    
    function JVHooks(){
		$args = func_get_args();
		call_user_func_array(array(&$this, '__construct'), $args);
	}
    
    public static function &getInstance($layouts = null, $options = null){
        static $instance;

		if (empty($instance)) {
            $instance = new JVHooks($layouts, $options);
		}
        
        return $instance;
    }
    
    public function __construct($layouts, $options) {
        $this->layouts = $layouts;
        $this->options = $options;
    }
    
    public function putHead(){
        $data = $this->getHeadData();
        $this->setHeadData($data);
        
    }
    
    protected function setHeadData($data){
        require_once(dirname(__FILE__).DS.'minify'.DS.'UriRewriter.php');
        $menus    = JSite::getMenu();  
        $browser  = new Browser();
        $itemId   = isset($menus->getActive()->id) ? $menus->getActive()->id : '';
        $document = JVFactory::getFramework()->getDocument();  
        $docHead  = $document->getHeadData(); 
        
        $docHead['links']       = $data->_links;
        $docHead['scripts']     = $data->_scripts;
        
        foreach($data->_script as $key => $value){
            if(isset($docHead['script'][$key])){
                $docHead['script'][$key] = $value.$docHead['script'][$key];
            }else{
                $docHead['script'][$key] = $value;
            }
        }
        
        foreach($data->_style as $key => $value){
            if(isset($docHead['style'][$key])){
                $docHead['style'][$key] = $value.$docHead['style'][$key];
            }else{
                $docHead['style'][$key] = $value;
            }
        }
        
        foreach($data->_custom as $key => $value){
            if(isset($docHead['custom'][$key])){
                $docHead['custom'][$key] = $value.$docHead['custom'][$key];
            }else{
                $docHead['custom'][$key] = $value;
            }
        }
        
        $docHead['styleSheets'] = $data->_styleSheets;
        
        $compress = $this->options->getCompress();
         
        if (isset($compress['gzip_compress']) && $compress['gzip_compress']) {
            $config = &JFactory::getConfig();                
            $config->setValue('gzip', '1');
        }
        
        if(JVFactory::getUserAgent() != 'standard'){
            $compress['css_compress'] = false;
            $compress['js_compress'] = false;
        }
        
        if(isset($compress['css_compress']) && $compress['css_compress']){
            $cache_css = 'css-' . md5('cache_css'.$itemId.JVFactory::isRTL().$browser->getBrowser().$this->options->getTemplateColor()) . '.php';  
            $data = '';

            if(is_array($docHead['styleSheets'])){                
                foreach($docHead['styleSheets'] as $styleSheets => $att){
                    $content = '';                    
                    if(preg_match('/http/', $styleSheets)){
                        if(preg_match('/'.preg_quote(JURI::root(), '/').'/', $styleSheets) || preg_match('/fonts.googleapis.com/', $styleSheets)){
                            $content     = @JFile::read($styleSheets);  unset($docHead['styleSheets'][$styleSheets]);                           
                            $styleSheets = str_replace(JURI::root(), JURI::root(true).'/', $styleSheets);
                        }
                    }else{
                        if(preg_match('/templates/', $styleSheets)){
                            $content = @JFile::read(JURI::base().str_replace(JURI::root(true).'/templates', '/templates', $styleSheets));
                        }else{
                            $content = @JFile::read(JURI::root().str_replace(JURI::root(true), '', $styleSheets));    
                        }
                        
                        unset($docHead['styleSheets'][$styleSheets]);
                    }
                    
                    if(preg_match('/'.preg_quote($this->layouts->getBaseThemesUrl(), '/').'/', $styleSheets)){
                        $content = str_replace('../images',$this->layouts->getBaseThemesUrl().'/images',$content); 
                    }elseif(!preg_match('/'.preg_quote($this->layouts->getThemesUrl(), '/').'/', $styleSheets)){
                        $content = Minify_CSS_UriRewriter::rewrite( $content, $this->getCssDir($styleSheets)); 
                    } 
                    
                    if(isset($att['media']) && $att['media'] != '') {
                        $content = '@media '.$att['media'].'{'.$content.'}';
                    } 
                                        
                    $data .= $content;
                }
            }
            
            $data .= $docHead['style']['text/css']; unset($docHead['style']['text/css']);
            if ($data != '' && $this->writeCache($this->addCacheSetting($data,'text/css'), $cache_css, $this->layouts->layoutPath() . DS . 'cache')) {                      
                $cssurl = $this->layouts->getThemesUrl() . '/cache/' . $cache_css;
                $docHead['styleSheets'][$cssurl] = array('mime' => 'text/css', 'media' => null, 'attribs'=>array());
            }
        }
        
        if(isset($compress['js_compress']) && $compress['js_compress']){
            $cache_js = 'js-' . md5('cache_js'.$itemId.JVFactory::isRTL().$browser->getBrowser().$this->options->getTemplateColor()) . '.php';
            $data     = '';
            
            if(is_array($docHead['scripts'])){
                $content = '';
                foreach($docHead['scripts'] as $scripts => $att){
                    
                    if(preg_match('/http/', $scripts)){
                        $content = @JFile::read($scripts);
                    }else{
                        $content = @JFile::read(JPATH_ROOT.str_replace(JURI::root(true), '', $scripts)); 
                    }
                    
                    $data .= $content;                    
                    unset($docHead['scripts'][$scripts]);
                }
            }
            
            $data .= $docHead['script']['text/javascript']; 
            unset($docHead['script']['text/javascript']);
            
            if ($data != '' && $this->writeCache($this->addCacheSetting($data,'text/javascript'), $cache_js, $this->layouts->layoutPath() . DS . 'cache')) {                      
                $jsurl = $this->layouts->getThemesUrl() . '/cache/' . $cache_js;
                $docHead['scripts']   = array();
                $docHead['scripts'][$jsurl] = array( 'mime' => 'text/javascript', 'defer' => null, 'async'=>null);
                
            }
        }
        
        $document->setHeadData($docHead);
    }
    
    protected function getCssDir($csslink){
        $styleSheet = str_replace('/', DS, $csslink);
        $filePath    = JPATH_ROOT.substr($styleSheet, strlen(JURI::base(true)), strlen($styleSheet));                        
        
        if(file_exists($filePath)){
            $pathInfo = pathinfo($filePath);
            $csslink  = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : $csslink;
        }
        
        return $csslink;
    }
    
    protected function getHeadData(){
        $this->fromBlock('head');
        $this->getStyle($this->options->getParam('layout_type_name'));  
            
        return $this;
    }
    
    private function fromBlock($block){
        $headData = array();
        $head     = $this->layouts->getBlock($block);
        
        if(isset($head['items']) && is_array($head['items'])){
            foreach($head['items'] as $headitem){
                if($headitem['tag'] != 'tmpl'){                    
                    $path  = (isset($headitem['path']) && $headitem['path'] == 'base_theme') ? $this->layouts->getBaseThemesUrl().'/' : $this->layouts->getThemesUrl().'/';  
                    
                    if(isset($headitem['name']) == false){
                        if(isset($headitem['names'])){
                            $items = (array) explode(',', $headitem['names']);    
                        }else{
                            $items = array($headitem);
                        }
                            
                    }else{
                        $items = null;
                    }                     
                    
                    if(count($items)){
                        foreach($items as $item){

                            switch($headitem['tag']){                                
                                case 'scriptfile':
                                    $this->addScript($path.'js/'.$item.'.js');
                                break;
                                
                                case 'stylefile':
                                
                                    if(isset($headitem['rtl'])){
                                        if($headitem['rtl'] == true && JVFactory::isRTL() == true){
                                            $this->addStyleSheet($path.'css/'.$item.'.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);     
                                        }
                                    }elseif(isset($headitem['ie'])) {
                                        $browser = new Browser();
                                        if($browser->isBrowser('IE')){
                                            $this->addStyleSheet($path.'css/'.$item.'.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);
                                        } 
                                    }else{
                                        $this->addStyleSheet($path.'css/'.$item.'.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);
                                    }
                                    
                                break;  
                                                              
                                case 'addonstyle':                                
                                    $this->fromAddon();  
                                break;
                                
                                case 'extensionstyle':                                
                                    $this->fromDocument();   
                                break;
                                
                                case 'gfont':
                                    $this->getGfont(); 
                                break;
                                
                                case 'customheadtag':
                                    $this->addCustomTag(str_replace(array('base_theme', 'current'), array($this->layouts->getBaseThemesUrl(), $this->layouts->getThemesUrl()), $headitem['data']));
                                break;
                                
                            }
                       }
                   }                    
                } 
            }
        }               
    }
    
    protected function getGfont(){
        $doc = JFactory::getDocument();
        $params     = JVFactory::getParameter();
        $fontparam  = $params->getGfont();
        $font_setup = Gfont::getFontSettup($this->layouts->layoutPath().DS.'googlefont');        
        $fonturl    = 'http://fonts.googleapis.com/css?family=';
        $url = array();
        
        foreach($fontparam as $fontname => $val){
            if($val != '' && isset($font_setup[$fontname])){
                $name = Gfont::getFontname($val);
                $url[] = str_replace(" ", "+", $name);   
                if($font_setup[$fontname] == 'body'){
                    $this->addStyleDeclaration( "{$font_setup[$fontname]} {font-family:'{$name}', ".$this->options->getFontFamily()."}");
                    $this->options->set('fontfamily', '0');
                } else{
                    $this->addStyleDeclaration( "{$font_setup[$fontname]} {font-family:'{$name}'}");
                }                    
                
            }                    
        }
        if(count($url)){
            $url = implode('|',$url);
            $this->addStyleSheet($fonturl.$url);
        }
    }
    
    private function fromAddon(){        
        $js = $this->initMenu();
        if($this->options->enableLazyLoad()){
			$js .= "new JVLazyLoad({selectors: '".$this->options->lazyLoadSelector()."'});";
		}
		if($this->options->enableBackToTop() && JVFactory::getUserAgent() == 'standard'){
			$js .= "new JVTop();";
		}
        
        $this->addScriptDeclaration("window.addEvent('domready', function(){". preg_replace("/[\r\n\s]+/",' ',$js) ."});");


    }
    
    public function fromDocument(){
        $document = JVFactory::getFramework()->getDocument();
        $docHead  = $document->getHeadData(); 
                
        if(isset($docHead['scripts'])){
             $this->_scripts = array_merge($this->_scripts, (array) $docHead['scripts']); 
             $docHead['scripts'] = array();
        }
        
        if(isset($docHead['_script'])){
            $this->_script  = array_merge($this->_script, (array) $docHead['_script']); 
            $docHead['_script'] = array();   
        }
        
        if(isset($docHead['styleSheets'])){
             $this->_styleSheets = array_merge($this->_styleSheets, (array) $docHead['styleSheets']);   
             $docHead['styleSheets'] = array(); 
        }
        
        if(isset($docHead['links'])){
             $this->_links = array_merge($this->_links, (array) $docHead['links']);    
             $this->_links = array_unique($this->_links);
             $docHead['links'] = array();
        }
        
        if(isset($docHead['_style'])){
            $this->_style = array_merge($this->_style, (array) $docHead['_style']); 
            $docHead['_style'] = array();   
        }
        
        if(isset($docHead['_custom'])){
            $this->_custom = array_merge($this->_custom, (array) $docHead['_custom']);
            $docHead['_custom'] = array();
        }
        
        $document->setHeadData($docHead);
    }     
    
    /**
     * Custom style
     * 
     * @param string $layout_type_name layout type
     * @access public
     * @return void
     */
    public function getStyle($layout_type_name = 'left-main-right') {
        $params        = $this->options;   
        $layouts       = JVFactory::getJVLayout();    
        $useragent     = JVFactory::getUserAgent();        
        $templatewidth = $params->getTemplateWidth();
        $main          = $params->getMainWidth();
        $mainbody      = $params->getMainBodyWidth();
        $sidebar1      = $params->getSidebarWidth($layouts->getSideBar1());
        $sidebar2      = $params->getSidebarWidth($layouts->getSideBar2());
        $space         = $params->getSpaceWidth();
        $fontsize      = $params->getFontSize();
        $fontfamily    = $params->getFontFamily();        
        
        if($fontfamily != ''){
            $this->addStyleDeclaration('body {font-family: '.$fontfamily.';}');
        }
        
        $search = array(
            'jvframework_fontsize','jvframework_fontfamily','jvframework_templatewidth',
            'jvframework_sidebar2_name', 'jvframework_sidebar2', 'jvframework_sidebar1_name',
            'jvframework_sidebar1', 'jvframework_mainbody', 'jvframework_main','jvframework_space'
        );
                
        $replace = array(
            $fontsize, $fontfamily, $templatewidth, $layouts->getSideBar2(),
            $sidebar2, $layouts->getSideBar1(), $sidebar1,$mainbody,$main,$space
        );
        
        $cssmobile = '';
        if($useragent !='standard'){
            $cssmobile = $this->getSpecialCss($useragent, $search, $replace); 
            $this->addStyleDeclaration($cssmobile);                    
        }
        
        if ($params->getLogoImage() != -1) {
            $this->addStyleDeclaration("div#logo a{background: url('".JURI::base(true)."/images/".$params->getLogoImage()."') no-repeat center}");
        }        
        
        $css = $this->getSpecialCss($useragent, $search, $replace);
             
        if($css != ''){            
            $this->addStyleDeclaration(preg_replace("/[\r\n\s]+/",' ',$css));
        }
         
        $templatecolor = $params->getTemplateColor();
        if($templatecolor != '-1' && file_exists($layouts->layoutPath().DS.'css'.DS.'colors'.DS.$templatecolor.'.css')){
            $this->addStyleSheet($layouts->getThemesUrl().'/css/colors/'.$templatecolor.'.css');
        }
        
        $this->addStyleDeclaration($this->genGrid()); 
    }
    
    protected function genGrid($columns = 16, $column_size = 60, $column_gutter = 20){
        $css = $gname = array();
        
        for($n = 1; $n <= $columns; $n++){
            $gname[] = '.u-1-'.$n;
            $css[]   = '.u-1'.($n != 1 ? '-'.$n.'{width:' . round(100/($n), 4) . '%;}' : '{display: block}');
            
            for($i = 2; $i < $n; $i++){
                $css[]  = ".u-".$i.'-'.$n.'{width: '.round(($i/$n*100), 4).'%}';
                $gname[]= ".u-".$i.'-'.$n;
            }
            
        }       
        return implode('', $css);
    }
    
    public function getSpecialCss($useragent, $search, $replace){
        $path1    = $this->layouts->layoutPath() . DS . 'special_css'. DS ;        
        $path2    = $this->layouts->templatePath(). 'basethemes' . DS . 'special_css' . DS;
        
        if($useragent == 'standard'){
            if(JFile::exists($path1.'standard.css')){
                $css = JFile::read($path1.'standard.css');
            }else{
                $css = JFile::read($path2.'standard.css');
            }            
        }else{
            if(JFile::exists($path1.'mobiles.css')){
                $css = JFile::read($path1.'mobiles.css');
            }else{
                $css = JFile::read($path2.'mobiles.css');
            }
        }
        
        if($css == '') return;
        
        $regex = "/<([^\s^}^{]*)?>/";
        preg_match_all($regex, $css, $matches);
        
        if(count($matches[0])){
            foreach($matches[0] as $index => $match){
                $val = str_replace($search, $replace, $matches[1][$index]);
               
                if(preg_match("/^(\d|-)/",$val)){                    
                    $val = calculate_string($val);
                }
                
                $css = preg_replace("/".preg_quote($match, "/")."/",$val,$css);
            }
        }
        
        return $css;
    }
    
    /**
     * Init menu
     * 
     * @access public 
     * @return string js menu.
     */
    public function initMenu() {
        $params = JVFactory::getParameter();
        $js = '';
        $css = array();
        $menutype = $params->getMenuStyle();
        $fxmode   = $params->getMenuFxMode();
        
        if ($params->enableJVMenu()) {
            $js .= "new JVMenu('.mainmenu', {
					menuType: '" . $menutype . "',
					fxDuration: " . $params->getMenuFxDuration() . ",
					fxTransition: Fx.Transitions." . $params->getMenuFxTransition() . ($params->getMenuFxTransition() != 'linear' ? "." . $params->getMenuFxEase() : '') . ",
					fxMode: '" . $fxmode . "',
					fxShowDelay: '" . $params->getFxShowDelay() . "',
					fxHideDelay: '" . $params->getMenuFxHideDelay() . "',
					clickToOpen: " . $params->getMenuClickToOpen() . "
				});\n";
           $this->addStyleSheet($this->layouts->getThemesUrl().'/css/horizontal.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);
        }else{           
            $this->addStyleSheet($this->layouts->getThemesUrl().'/css/horizontal.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);
        }

        if ($params->enableVerticalMenu()) {
            $js .= "new JVVMenu('.vertical', {
					menuType: '" . $params->getVMenuStyle() . "',
					fxDuration: " . $params->getVMenuFxDuration() . ",
					fxTransition: Fx.Transitions." . $params->getVMenuFxTransition() . ($params->getVMenuFxTransition() != 'linear' ?
                "." . $params->getVMenuFxEase() : '') . ",
					fxMode: '" . $params->getVMenuFxMode() . "',
					fxShowDelay: '" . $params->getVFxShowDelay() . "',
					fxHideDelay: '" . $params->getVMenuFxHideDelay() . "',
					clickToOpen: " . $params->getVMenuClickToOpen() . "
				});\n";
            $this->addStyleSheet($this->layouts->getThemesUrl().'/css/vertical.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);
        }

        if ($params->enableAccordionMenu()) {
            $js .= "new JVAMenu('.accordion', {					
					fxDuration: " . $params->getAMenuFxDuration() . ",
					fxTransition: Fx.Transitions." . $params->getAMenuFxTransition() . ($params->getAMenuFxTransition() != 'linear' ?
                "." . $params->getAMenuFxEase() : '') . ",
					fxMode: '" . $params->getAMenuFxMode() . "',
					clickToOpen: " . $params->getAMenuClickToOpen() . ",
					alwaysHide: " . $params->getAMenuAlwaysHide() . "
				});\n";
            $this->addStyleSheet($this->layouts->getThemesUrl().'/css/accordion.css', 'text/css', isset($headitem['media']) && $headitem['media'] !='' ? $headitem['media'] : null);
        }
        
        return $js;
    }    
    /**
	 * Adds a linked script to the page
	 *
	 * @param	string  $url		URL to the linked script
	 * @param	string  $type		Type of script. Defaults to 'text/javascript'
	 * @param	bool	$defer		Adds the defer attribute.
	 * @param	bool	$async		Adds the async attribute.
	 * @access	public
	 */
	function addScript($url, $type = "text/javascript", $defer = false, $async = false) {
		$this->_scripts[$url]['mime'] = $type;
		$this->_scripts[$url]['defer'] = $defer;
		$this->_scripts[$url]['async'] = $async;
	}

	/**
	 * Adds a script to the page
	 *
	 * @access	public
	 * @param	string  $content	Script
	 * @param	string  $type		Scripting mime (defaults to 'text/javascript')
	 * @return	void
	 */
	function addScriptDeclaration($content, $type = 'text/javascript')
	{
		if (!isset($this->_script[strtolower($type)])) {
			$this->_script[strtolower($type)] = $content;
		} else {
			$this->_script[strtolower($type)] .= chr(13).$content;
		}
	}

	/**
	 * Adds a linked stylesheet to the page
	 *
	 * @param	string  $url	URL to the linked style sheet
	 * @param	string  $type	Mime encoding type
	 * @param	string  $media  Media type that this stylesheet applies to
	 * @access	public
	 */
	function addStyleSheet($url, $type = 'text/css', $media = null, $attribs = array())
	{
		$this->_styleSheets[$url]['mime']		= $type;
		$this->_styleSheets[$url]['media']		= $media;
		$this->_styleSheets[$url]['attribs']	= $attribs;
	}

	/**
	 * Adds a stylesheet declaration to the page
	 *
	 * @param	string  $content	Style declarations
	 * @param	string  $type		Type of stylesheet (defaults to 'text/css')
	 * @access	public
	 * @return	void
	 */
	function addStyleDeclaration($content, $type = 'text/css')
	{
		if (!isset($this->_style[strtolower($type)])) {
			$this->_style[strtolower($type)] = $content;
		} else {
			$this->_style[strtolower($type)] .= chr(13).$content;
		}
	}
    
    /**
	 * Adds a custom html string to the head block
	 *
	 * @param string The html to add to the head
	 * @access   public
	 * @return   void
	 */

	function addCustomTag( $html )
	{
		$this->_custom[] = trim( $html );
	}  
    
    /**
	 * Adds a shortcut icon (favicon)
	 *
	 * <p>This adds a link to the icon shown in the favorites list or on
	 * the left of the url in the address bar. Some browsers display
	 * it on the tab, as well.</p>
	 *
	 * @param	 string  $href		The link that is being related.
	 * @param	 string  $type		File type
	 * @param	 string  $relation	Relation of link
	 * @access	public
	 */
	function addFavicon($href, $type = 'image/x-icon', $relation = 'shortcut icon')
	{
		$href = str_replace( '\\', '/', $href );
		$this->_links[] = '<link href="'.$href.'" rel="'.$relation.'" type="'.$type.'"';
	}
    
    /**
     * Doctype code
     * 
     * @access public 
     * @return string doctype.
     */
    public function docType() {
        $document = JVFactory::getFramework();
        $browser  = new Browser(); // Detect browser and platform.
        
        $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
         
        if ($browser->getBrowser() == 'IE' && JVFactory::isRTL()) {
            $doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">';
        }
       
        $doctype .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $document->get('Language') . '" lang="' .$document->get('Language') . '" >' . "\n";
        
        
        return $doctype;
    }
    
    /**
     * Write js, css Cache
     */
    public function writeCache($data, $filename, $path, $dnm = false) {  
        $file   = $path . DS . "{$filename}";
        $file_expire = $path . DS . "{$filename}_expire";
        $expire = 0;
        if (!JFolder::exists ($path)) {
			if (!JFolder::create ($path)) return false;
		}
		if (!JFile::exists ($path.DS.'index.html')) {
            $html = '<html><body></body></html>';
			if (!JFile::write ($path.DS.'index.html', $html)) return false; 
		}
        
        $isExpire = false;
        if(JFile::exists($file_expire)){
            $expire = JFile::read($file_expire);
        }        
        if(time() >= $expire){
            $isExpire = true;
        }        
        
        if (!JFile::exists($file) || !JFile::exists($file_expire) || $isExpire) {
            if(stripos($file,'js')){
                $data = JSMin::minify($data);
            }
            if(stripos($file,'css')){
                $data = Minify_CSS_Compressor::process($data);
            }            
       	    if (!JFile::write ($file, $data)) return false;
            $time = time() + 60 * 1440;
            
            if (!JFile::write ($file_expire, $time)) return false;
        }
        
        if (JFile::exists($file)) {
            return true;
        }
        return false;            
    }
    
    /**
     * Get Instance Jcache
     * 
     * @access public 
     * @return object reference to a cache adapter object
     */
    public function getCache() {
        $conf    =& JFactory::getConfig();

        $options = array(
                'cachebase'     => JPATH_SITE . DS . 'cache', 
                'defaultgroup'  => 'jv', 
                'lifetime'      => $conf->getValue('config.cachetime') * 60,
                // minutes to seconds
                'handler'       => $conf->getValue('cache_handler'), 
                'caching'       => false, 
                'language'      => $conf->getValue('config.language'), 
                'storage'       => 'file'
                );
        $params = JVFactory::getParameter();
        $cache  = &JCache::getInstance('callback', $options);
        $enableCache = (bool) $params->getParam('layoutCache','0');
        $cache->setCaching($enableCache);

        return $cache;
    }
    
    
    /**
     * Add Cache Setting
     * 
     * @param  string $content content to add code.
     * @param  string $type    content type
     * @access public 
     * @return string content.
     */
     public function addCacheSetting($content, $type = 'text/css') {        
        $cache = '<?php
ob_start ("ob_gzhandler");
header("Content-type: ' . $type . '; charset: UTF-8");
header("Cache-Control: must-revalidate");
$expires_time = 1440;
$offset = 60 * $expires_time ;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr);
$LasMdf = "Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT";
header($LasMdf);
header("ETag: \'3e86-410-3596fbbc\'");
                ?>' . "\n" . $content;

        return $cache;
    }
    
}

if(!function_exists('calculate_string')){
    function calculate_string( $mathString )	{
    	$mathString = trim($mathString);     // trim white spaces
    	$mathString = preg_replace ('/^0-9\+-\*\/\(\)/', '', $mathString);    // remove any non-numbers chars; exception for math operators
    
    	$compute = create_function("", "return (" . $mathString . ");" );
    	return 0 + $compute();
    }
}